from datetime import datetime, timedelta
from logging.handlers import RotatingFileHandler
import os
from flask import Flask, make_response, request,jsonify
import logging
from src.config import config

# from flask_script import Manager, Server
import json

from src.common.qywx_util import QYWXUtil
from src.common.wx_util import WxUtil
from src.exts import rate_limit, tryCatch
from src.spider import Spider
from src.thread_busi import calculate_hanlder, fetch_all_measure_history, fetch_fuquan_all, fetch_fuquan_daliy, fetch_hist_sw_ind_comp, fetch_overall_market_trend, fetch_stock_daily, fetch_stocks, fetch_sw_ind, fetch_sw_index_daily, pre_caculator, task_worker
from flask_apscheduler import APScheduler

from src.mxtf_api import MxtfApi
app = Flask(__name__)
app.secret_key = b'_5#y2L"F4Q8z\n\xec]/'



# 创建一个 RotatingFileHandler 对象
handler = RotatingFileHandler('app.log', maxBytes=10*1024*1024, backupCount=5)

# 设置日志记录级别
handler.setLevel(logging.DEBUG)

# 创建一个日志记录格式
formatter = logging.Formatter('{"@timestamp":"%(asctime)s","@version":"1.0.0","level":"%(levelname)s","message":"%(message)s","app:"pre-calculator"}')
handler.setFormatter(formatter)
app.logger.setLevel(logging.DEBUG)
# 添加处理器到 Flask 的日志记录器
app.logger.addHandler(handler)

logging.getLogger("urllib3").setLevel(logging.DEBUG)


@app.route("/hello", methods=["GET"])
@tryCatch
def hello_world():
    return jsonify({"result":"ok"})

@app.route("/spider/fetch_sw_index_daily", methods=["GET"])
def spider():
    '''爬取fetch_sw_index_daily数据'''
    try:
        print("开始抓取数据")
        fetch_sw_index_daily.delay(app.logger)
    except Exception as e:
        print(e)
    return jsonify({"result":"ok"})
@app.route("/spider/fetch_hist_sw_ind_comp",methods=["GET"])
def main_fetch_hist_sw_ind_comp():
    '''爬取申万行业分类'''
    try:
        print("开始抓取数据")
        fetch_hist_sw_ind_comp.delay(app.logger)
    except Exception as e:
        print(e)
    return jsonify({"result":"ok"})
@app.route("/spider/fetch_stock_daily",methods=["GET"])
def main_fetch_stock_daily():
    '''爬取fetch_stock_daily'''
    try:
        start_date = request.args.get('start_date','2020-01-01')
        if not start_date:
            start_date = '2020-01-01'
        stock = request.args.get('stock')
        print("开始抓取数据")
        fetch_stock_daily.delay(start_date,stock,app.logger)
    except Exception as e:
        print(e)
    return jsonify({"result":"ok"})

@app.route("/spider/fetch_fuquan_all",methods=["GET"])
def main_fetch_fuquan_all():
    '''爬取复权因子'''
    try:
        stock = request.args.get('stock')
        print("开始爬取复权因子")
        fetch_fuquan_all.delay(stock,app.logger)
    except Exception as e:
        print(e)
    return jsonify({"result":"ok"})

@app.route("/spider/fetch_fuquan_daliy",methods=["GET"])
def main_fetch_fuquan_daliy():
    '''每日爬取复权因子'''
    try:
        
        print("每日开始爬取复权因子")
        fetch_fuquan_daliy.delay(app.logger)
    except Exception as e:
        print(e)
    return jsonify({"result":"ok"})

@app.route("/spider/fetch_stocks",methods=["GET"])
def main_fetch_stocks():
    '''爬取股票信息'''
    try:
        print("开始爬取股票信息")
        fetch_stocks.delay(app.logger)
    except Exception as e:
        print(e)
    return jsonify({"result":"ok"})
@app.route("/spider/fetch_sw_ind",methods=["GET"])
def main_fetch_sw_ind():
    '''爬取fetch_sw_ind数据'''
    try:
        print("开始抓取数据")
        fetch_sw_ind.delay(app.logger)
    except Exception as e:
        print(e)
    return jsonify({"result":"ok"})

@app.route("/spider/fetch_overall_market_trend",methods=["GET"])
def main_fetch_overall_market_trend():
    '''爬取大盘数据'''
    try:
        print("开始抓取大盘数据")
        fetch_overall_market_trend.delay(app.logger)
    except Exception as e:
        print(e)
    return jsonify({"result":"ok"})

@app.route("/spider/fetch_all_measure_history", methods=["GET"])
def main_fetch_all_measure_history():
    try:
        fetch_all_measure_history.delay(app.logger)
    except Exception as e:
        print(e)
    return jsonify({"result":"ok"})

@app.route("/adminget_user_token", methods=["GET"])
def main_get_user_token():
    try:
        email = request.args.get('email')
        if not email:
            return jsonify({"error":"email is empty"})
        return WxUtil(logger=app.logger).get_user_token(email)
    except Exception as e:
        print(e)
    return jsonify({"result":"ok"})


@app.route("/wx/refresh_accesstoken", methods=["GET"])
def main_refresh_accesstoken():
    try:
        util = WxUtil(logger=app.logger)
        util.refresh_accesstoken(request.args.get('force',0))
        return jsonify({"result":"ok"})
    except Exception as e:
        return jsonify({"error":str(e)})

@app.route("/wx/set_accesstoken", methods=["GET"])
def main_set_accesstoken():
    try:
        util = WxUtil(logger=app.logger)
        util.set_accesstoken(request.args.get('token',0))
        return jsonify({"result":"ok"})
    except Exception as e:
        return jsonify({"error":str(e)})
    
@app.route("/wx/get_qrcode", methods=["GET"])
def main_get_qrcode():
    try:
        util = WxUtil(logger=app.logger)
        img_data = util.get_qrcode(request.args.get('trial','0'))
        response = make_response(img_data)
        response.headers['Content-Type']='image/png'
        return response
    except Exception as e:
        return jsonify({"error":str(e)})

@app.route("/init/regional", methods=["GET"])
def main_regional():
    try:
        s = Spider(logger=app.logger)
        s.init_regional_data()
        return jsonify({"result":"ok"})
    except Exception as e:
        return jsonify({"error":str(e)})

@app.route("/pre_caculate", methods=["POST"])
@rate_limit(10,5)
def pre_caculate():
    '''
    {  
    "caculateId":"18931684651312",
    "stock_no":"股票代码",
        "broker_id":"券商编号",
        "begin_time":11111,// '维权跨度开始时间',
        "end_time":11111,// '维权跨度结束时间',
        "trade_list":[{  
            "operation_time":11111,//操作时间
            "direction":11111,//方向(0-卖出,1买入)
            "price":11111,//买入/卖出价格
            "qty":11111,//买入/卖出数量
            "amount":11111,//总金额
            },{  
            "operation_time":11111,//操作时间
            "direction":11111,//方向(0-卖出,1买入)
            "price":11111,//买入/卖出价格
            "qty":11111,//买入/卖出数量
            "amount":11111,//总金额
            }]
        }
    '''
    try:
        data = request.get_json()
        app.logger.debug(f"开始测算{json.dumps(data)}")
        pre_caculator.delay(data,logger=app.logger)
    except Exception as e:
        print(e)
    return jsonify({"result":"ok"})

@app.route("/open/send_msg", methods=["GET"])
@tryCatch
def main_send_msg():
    QYWXUtil(app.logger).send_robot_notic(request.args.get('title'),request.args.get('msg'))

@app.route("/open/calculate_hanlder", methods=["GET"])
@tryCatch
def main_calculate_hanlder():
    calculate_hanlder(app.logger,request.args.get('taskId'))
    return 'ok'

scheduler = APScheduler()
scheduler.init_app(app)
scheduler.start()
def one_time_task():
    for i in range(0,config.worker):
        task_worker.delay(app.logger)

if os.environ.get("FLASK_ENV")!='dev':
    # 安排一次性任务在5秒后执行
    one_time_job = scheduler.add_job(
        id='One Time Task',
        func=one_time_task,
        trigger='date',
        run_date=datetime.now() + timedelta(seconds=config.delay)
    )